#include "ParticleEffect.h"

ParticleEffect::ParticleEffect(ID3DXSprite *sprite)
{
	mSprite = sprite;
}

void ParticleEffect::AddParticles(int numParticles, SpriteData &spriteData, float minScale, float maxScale, float minVel, float maxVel, float minAngVel, float maxAngVel, float lifeTime, physics::Vector3 position, bool alphaFade, physics::Vector3 gravity)
{
	if (gravity != physics::Vector3(0, 0, 0))
	{
		mAffectedByGravity = true;
		mGravity = gravity;
	}
	else
		mAffectedByGravity = false;

	physics::Particle* part;

	for (int i = 0; i < numParticles; i++)
	{
		float scale = GetRandomFloat(minScale, maxScale);
		float velocity = GetRandomFloat(minVel, maxVel);
		float angularVel = GetRandomFloat(minAngVel, maxAngVel);
		part = new physics::Particle(mSprite, spriteData, scale, velocity, angularVel, lifeTime, position, alphaFade);
		mParticles.push_back(part);
	}
}

ParticleEffect::~ParticleEffect()
{
	while (mParticles.size() > 0)
	{
		Particles::iterator i = mParticles.begin();
		delete *i;
		mParticles.erase(i);
	}
}

void ParticleEffect::UpdateViewProjMatrix(D3DXMATRIX &viewProj)
{
	mViewProj = viewProj;
}

void ParticleEffect::Update(float dt)
{
	Particles::iterator i = mParticles.begin();
	while (i != mParticles.end())
	{
		if (mAffectedByGravity)
			(*i)->applyForce(mGravity);

		(*i)->integrate(dt);
		i++;
	}
}

void ParticleEffect::Render()
{
	Particles::iterator i = mParticles.begin();
	while (i != mParticles.end())
	{
		(*i)->Render(mViewProj);
		i++;
	}
}

void ParticleEffect::EndFrame()
{
	Particles::iterator i = mParticles.begin();
	while (i != mParticles.end())
	{
		(*i)->clearAccumulators();
		(*i)->calculateDerivedData();
		i++;
	}
}

bool ParticleEffect::HasStopped()
{
	Particles::iterator i = mParticles.begin();
	bool hasStopped = true;
	while (i != mParticles.end())
	{
		if (!(*i)->mSprite->HasStopped())
			hasStopped = false;
		i++;
	}

	return hasStopped;
}